package com.db.onlinedb.controller;

import com.db.onlinedb.entity.Table;
import com.db.onlinedb.utils.Conn;
import com.db.onlinedb.utils.ConnectionMap;
import com.db.onlinedb.utils.LinkName;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;


import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 *
 */
@RestController
@CrossOrigin(origins = "*", maxAge = 3600)
public class DbController {
    @PostMapping("/getTable")
    public Table getDb(String lh, String DbName, String DbTable) throws SQLException {
        System.out.println(lh);
        String sql = "use " + DbName;
        Connection con = ConnectionMap.findConn(lh);      //得到连接
        Statement statement = con.createStatement();
        statement.execute(sql);
        String select = "select * from " + DbTable;
        ResultSet rs = statement.executeQuery(select);   //返回查询结果集
        ResultSetMetaData resultSetMetaData = rs.getMetaData(); //数据表结构
        List<String> column = new ArrayList<>();
        List<List<String>> tableData = new ArrayList<>();
        //获取列名
        for (int i = 0; i < resultSetMetaData.getColumnCount(); i++) {
            String col_name = resultSetMetaData.getColumnName(i + 1);
            column.add(col_name);
        }
        while (rs.next()) {
            List<String> tmp = new ArrayList<>();
            for (int i = 0; i < resultSetMetaData.getColumnCount(); i++) {
                String a = rs.getString(i + 1);
                tmp.add(a);
            }
            tableData.add(tmp);
        }
        Table table = new Table(column, tableData);
        return table;
    }
}
